<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div>
      <el-row type="flex" justify="end">
        <template v-if="isShowBtnBar">
          <el-button
            v-if="showBtn('关联商品')"
            type="text"
            size="large"
            @click="handleAssociatedGoods"
            >关联商品</el-button
          >
          <el-button
            type="text"
            size="large"
            @click="handleExportData"
            :loading="loading.export"
            :disabled="tableData.length === 0"
            >模板导出</el-button
          >
          <a
            ><Upload
              :show-upload-list="false"
              :format="['xlsx', 'xls', 'csv']"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :on-format-error="handleUploadFormatError"
              :before-upload="handleBeforeUpload"
              :action="`${uploadBaseURL}sysback/update/product/basicinfo/saveBasicInfoToPage`"
              ><el-button type="text" size="large">模板导入</el-button></Upload
            ></a
          >
          <el-button
            type="text"
            size="large"
            @click="handleSaveData"
            :loading="loading.submit"
            :disabled="tableData.length === 0"
            >暂存</el-button
          >
          <el-button
            type="text"
            size="large"
            @click="handleSubmitData"
            :loading="loading.submit"
            :disabled="tableData.length === 0"
            >提交</el-button
          >
        </template>
        <template v-else>
          <el-button
            v-if="pageState.audit && !pageState.menu"
            type="text"
            size="large"
            @click="handleOpenAuditDialog"
            >审核</el-button
          >
        </template>
        <el-button
          v-if="isShowBackBtn"
          type="text"
          size="large"
          @click="handleGoBack"
          >返回</el-button
        >
      </el-row>
      <el-row class="format_table_wrap">
        <general-render-table
          :loading="loading.table"
          :data-source="tableData"
          :columns="tableColumns"
          @handleCancelSelect="handleCancelSelect"
        />
      </el-row>
      <el-row>
        <FooterFields :recordNo="recordNo" />
      </el-row>
    </div>
    <!-- 关联商品-SPU维度弹框 -->
    <spu-associated-dialog
      ref="spuModal"
      :columns="associatedGoods.columns"
      :requestApi="associatedGoods.requestApi"
      :requestParams="associatedGoods.requestParams"
      :distinctParams="associatedGoods.distinctParams"
      :isAccurateSearchClassify="true"
      @getRowList="getAssociatedGoodsAction"
    ></spu-associated-dialog>
    <!-- 审核弹框组件 -->
    <audit-dialog :visible.sync="auditDialogVisible" />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import AuditDialog from '@/components/common/dialog/auditDialog';
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
/* constants */
import { basicinfoRequiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import { EDIT_BASE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import {
  getAttributeTypeFn,
  performDifferentTypeMethodsFn
} from '@/pages/commodity/modules/utils';
import { getDealBaseDataToApiFn } from '@/pages/commodity/modules/utils/basicInfoRequireUtils';
import { generateHighlightNodeForSalePrice } from '@/utils/bizUtils';

export default {
  mixins: [spuDimensionMixins],
  components: {
    SpuAssociatedDialog,
    GeneralRenderTable,
    FooterFields,
    AuditDialog
  },
  data () {
    return {
      auditDialogVisible: false, // 审核弹框visible
      /* 关联商品弹框组件所需数据 */
      associatedGoods: {
        requestApi: {
          url: ['/sysback/update/product/basicinfo/getProductList'],
          type: 'post'
        },
        requestParams: basicinfoRequiredParams.requestParams,
        distinctParams: basicinfoRequiredParams.distinctParams,
        columns: [
          { type: 'selection', width: 60, align: 'center' },
          { title: '商品名称', key: 'productName', width: 160 },
          { title: 'SPU编码', key: 'spuNo', width: 200 },
          { title: '商品分类', key: 'categoryPath', width: 200 },
          { title: '管理区域', key: 'manageAreaName', width: 140 },
          { title: '品牌', key: 'brandName', width: 150 },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            fixed: 'right',
            width: 100
          }
        ]
      },
      loading: {
        table: false, // 表格加载loading
        submit: false, // 提交按钮loading
        export: false // 导出按钮loading
      },
      pageState: {
        menu: false, // 菜单
        view: false, // 查看
        edit: false, // 修改
        audit: false, // 审核
        single_sku: false, // SKU管理
        single_spu: false // SPU管理
      },
      footerFields: {}, // 表尾字段
      initTableColumns: [
        {
          title: 'SPU编码',
          key: 'spuNo',
          align: 'center',
          width: 150
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          align: 'center',
          width: 150
        }
      ],
      tableColumns: [], // sku表格列表字段
      tableData: [],
      conformShowBtnConditions: ['未提交', '审核未通过'], // 暂存按钮或提交按钮是否可显示的条件之一
      notConformShowBtnConditions: ['已提交', '审核中', '审核通过'],
      recordNo: '', // 单据号
      apiSourceList: {
        /* 查询基本信息-- 用单据号查询 */
        queryTableDataFromDocManage: {
          url: '/sysback/product/update/record/queryRecordBasicInfo',
          type: 'post'
        },
        /* 查询基本信息---uuid查询_来自SPU查询 */
        queryTableDataFromSpu: {
          url: '/sysback/update/product/basicinfo/queryBasicInfoListFromSpu',
          type: 'post'
        },
        /* 查询基本信息---uuid查询_来自SKU查询 */
        queryTableDataFromSku: {
          url: '/sysback/update/product/basicinfo/queryBasicInfoListFromSpu',
          type: 'post'
        },
        /* 单据信息-- 根据recordNo查询 */
        getFooterFieldsByRecordNo: {
          url: '/sysback/product/update/record/getByRecordNo',
          type: 'post'
        },
        /* 单据信息-- 根据productUuid查询 */
        getFooterFieldsByUuid: {
          url: '/sysback/product/update/record/queryRecordExist',
          type: 'post'
        },
        /*  查询单据信息---skuNo查询_来自SKU查询 */
        getFooterFieldsBySkuNo: {
          url: '/sysback/product/update/record/queryRecordExist',
          type: 'post'
        }
      },
      apiObj: {
        // 暂存
        saveBasicInfo: {
          url: '/sysback/update/product/basicinfo/saveBasicInfo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 提交
        commitBasicInfo: {
          url: '/sysback/update/product/basicinfo/commitBasicInfo', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 按商品导出基本信息
        exportPageToExcelPost: {
          url: '/sysback/update/product/basicinfo/exportPageToExcelPost', // 接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  watch: {
    '$route.path' (newValue) {
      this.$router.go(0);
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    // 展示基础按钮栏
    isShowBtnBar () {
      const { audit, view } = this.pageState;
      return !audit && !view;
    },
    // 展示返回按钮
    isShowBackBtn () {
      const { view, audit, menu } = this.pageState;
      return !view && !audit && !menu;
    },
    pageTitle () {
      let title = '修改基本信息';
      let { menu, view, audit } = this.pageState;
      if (menu) {
        return title;
      } // 从菜单修改sku页面进入
      if (view) {
        // 查看页面
        title = `${title}-表单查看页面`;
        return title;
      }
      if (audit) {
        // 审核页面
        title = `${title}-表单审核页面`;
        return title;
      }
      title = `${title}-表单修改页面`; // 修改页面
      return title;
    }
  },
  mounted () {
    this.initPageDataFn();
    this.tableColumns = _.cloneDeep(this.initTableColumns);
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    /* 初始化页面数据 */
    initPageDataFn () {
      let { recordNo, uuid, skuNo, type } = this.$route.query;
      if (!type && recordNo) {
        // 如果有单据号，但是没有type值，说明是从OA跳过来的查看页面
        type = 'view';
      }
      let pageType = type || 'menu';
      this.pageState[pageType] = true;
      if (!type) {
        return false;
      } // 如果没有type，表明是菜单页面，无需调用下面的逻辑方法
      this.recordNo = recordNo || '';
      let params = {
        recordNo,
        uuid,
        type,
        skuNo,
        apiSourceList: this.apiSourceList,
        commitType: 'basicInfo',
        getExistTableDataAction: this.getExistTableDataAction,
        initQueryExistRecordAction: () => {}
      };
      performDifferentTypeMethodsFn(params);
    },
    /* 获取已存在的表格数据方法 - 表单管理页面，SPU和SKU管理页面进入时调用，菜单界面的修改SKU不调用 */
    getExistTableDataAction (data) {
      let { api, params } = data;
      // 开始请求列表
      this.loading.table = true;
      ApiRequest(api.url, api.type, params, true)
        .then((res) => {
          this.loading.table = false;
          if (res.retStatus !== '1') {
            return false;
          }
          res.retData.forEach((row) => {
            row.uuid = row.productUuid;
            this.ASSOCIATED_GOODS({ row });
          });
          this.initTableDataFn(res.retData);
        })
        .catch(() => {
          this.loading.table = false;
        });
    },
    /* 初始化表格数据 */
    initTableDataFn (dataSource) {
      this.tableColumns = _.cloneDeep(this.initTableColumns);
      this.tableData = [];
      this.handleDealTableTh(dataSource);
      if (this.pageState.view || this.pageState.audit) {
        return false;
      } // 查看和审核页面不需要操作按钮
      this.tableColumns.push({
        title: '操作',
        key: 'action',
        fixed: 'right',
        width: 150
      });
    },
    /* 获取表格children格式的数据 */
    getChildrenFn (thItem) {
      let children = [
        {
          title: '原值',
          align: 'center',
          render: (h, { row }) => {
            return <div>{row[thItem.attrName].valueName}</div>;
          }
        }
      ];
      if (this.pageState.view || this.pageState.audit) {
        children.push({
          title: '现值',
          align: 'center',
          render: (h, { row }) => {
            return generateHighlightNodeForSalePrice(h, row[thItem.attrName].valueName, row[thItem.attrName].valueNameUpdate)
          }
        });
      } else {
        children.push({
          title: '现值',
          key: thItem.attrName,
          align: 'center',
          type: getAttributeTypeFn(thItem.attrType),
          width: thItem.attrType === '04' ? '180' : '120'
        });
      }
      return children;
    },
    /* 处理表头方法 */
    handleDealTableTh (dataSource) {
      this.tableData = dataSource.reduce((value, item, index) => {
        let { spuNo, productUuid, productNameFinal } = item;
        value.push({ spuNo, productUuid, productNameFinal });
        value[index].attrNameList = [];
        value[index].attrList = item.attrList;
        item.attrList.forEach((thItem) => {
          if (thItem.attrType === '04') {
            thItem.valueName = thItem.valueName
              ? _.clone(thItem.valueName).split(/,|，|\s+/)
              : []; // 以中英文逗号、空格（一个或多个）分割字符串
          }
          value[index][thItem.attrName] = thItem;
          value[index].attrNameList.push(thItem.attrName);
          index === 0 &&
            this.tableColumns.push({
              title: thItem.attrName,
              align: 'center',
              required: thItem.attrMust === '1' || false,
              children: this.getChildrenFn(thItem)
            });
        });
        return value;
      }, []);
    },
    /* 点击关联商品的事件 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
      /* this.$nextTick(() => {
        this.$refs.spuModal.getDataListAction();
      }); */
    },
    /* 删除表格对应行的方法 */
    handleCancelSelect (data) {
      let { row } = data;
      this.handleDeleteSpuRow(row, this.tableData, 'productUuid');
      this.getAssociatedGoodsAction();
    },
    /* 获取关联商品后的表格数据的方法 */
    getAssociatedGoodsAction () {
      let dataList = this.getListFromMapFn().map((value) => {
        return value.uuid;
      });
      if (dataList.length === 0) {
        this.tableData = [];
        return false;
      }
      // let data = { productKeyList: dataList.join(',') };
      this.loading.table = true;
      ApiRequest(
        `/sysback/update/product/basicinfo/queryBasicInfoList`,
        'post',
        dataList,
        false
      )
        .then((res) => {
          this.loading.table = false;
          if (res.retStatus !== '1') {
            return false;
          }
          this.initTableDataFn(res.retData);
        })
        .catch(() => {
          this.loading.table = false;
        });
    },
    /* 暂存 */
    handleSaveData () {
      if (this.tableData.length > EDIT_BASE_INFO_AMOUNT) {
        return this.$message.warning(
          `当前单据提交的行数不能超过${EDIT_BASE_INFO_AMOUNT}`
        );
      }
      let { submitResults, errorMessage } = getDealBaseDataToApiFn({
        tableData: this.tableData,
        type: 'modify'
      });
      if (errorMessage) {
        return this.$Message.warning(errorMessage);
      }
      let data = {
        recordNo: this.recordNo,
        inputList: submitResults
      };
      this.loading.submit = true;
      let { url, type } = this.apiObj.saveBasicInfo;
      return new Promise((resolve, reject) => {
        ApiRequest(url, type, data, false)
          .then((res) => {
            this.loading.submit = false;
            if (res.retStatus !== '1') {
              return false;
            }
            this.$message.success('暂存成功');
            this.recordNo = res.retData.recordNo;
            resolve(true);
          })
          .catch(() => {
            this.loading.submit = false;
          });
      });
    },
    /* 提交Action */
    submitDataAction () {
      this.handleSaveData().then((res) => {
        if (!res) {
          return false;
        }
        let data = {};
        let { url, type } = this.apiObj.commitBasicInfo;
        this.loading.submit = true;
        ApiRequest(`${url}?recordNo=${this.recordNo}`, type, data, false)
          .then((res) => {
            this.loading.submit = false;
            if (res.retStatus !== '1') {
              return false;
            }
            this.$message.success('提交成功');
            this.$router.push({ name: 'chageFromManageList' });
          })
          .catch(() => {
            this.loading.submit = false;
          });
      });
    },
    /* 提交 */
    handleSubmitData () {
      this.$Modal.confirm({
        title: '提示',
        content: '确认提交信息吗？',
        onOk: () => {
          this.submitDataAction();
        }
      });
    },
    /* 导出数据 */
    handleExportData () {
      let { submitResults } = getDealBaseDataToApiFn({
        tableData: this.tableData,
        type: 'modify'
      });
      let { url, type } = this.apiObj.exportPageToExcelPost;
      this.loading.export = true;
      ApiRequestExportTable(url, type, submitResults, false)
        .then((res) => {
          this.loading.export = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '修改基本信息.xlsx';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.loading.export = false;
          this.$message.error('导出失败');
        });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading.table = false;
      this.$Message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading.table = true;
      this.tableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (res) {
      this.loading.table = false;
      if (res.retStatus !== '1') {
        return this.$message.error(res.retMessage);
      }
      this.initTableDataFn(res.retData); // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading.table = false;
      this.$message.error('上传失败');
    },
    /* 打开审核弹框 */
    handleOpenAuditDialog () {
      this.auditDialogVisible = true;
    },
    // 返回上一页
    handleGoBack () {
      let routerName = 'chageFromManageList';
      if (this.pageState.single_spu) {
        routerName = 'SPUManageList';
      } else if (this.pageState.single_sku) {
        routerName = 'SKUManageList';
      }
      this.$router.push({ name: routerName })
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
